const router = require('express').Router()
const sql = require('./../sql')
const Student = require('./../sql/models/Student')
const utils = require('./../utils')
const xlsx = require('node-xlsx')
const urlencode = require('urlencode')
const fs = require('fs')
const path = require('path')
var multer = require('multer')
var upload = multer({ dest: './public/uploads/' })

//导出学生名单列表模板
router.get('/exportStudentModel', (req, res, next) => {
  let studentModel = []
  studentModel.unshift([
    '班级(写全称，例：网络工程171，信息安全171)',
    '长学号(1520173388)',
    '姓名',
    '性别(1为男，2为女，例：1)',
  ])
  // console.log(studentModel)
  let buffer = xlsx.build([{ name: 'studentModel.xlsx', data: studentModel }])
  res.setHeader('Content-Type', 'application/octet-stream')
  let name = urlencode('学生名单列表模板_' + +new Date() + '.xlsx', 'utf-8')
  res.setHeader('Content-Disposition', "attachment; filename* = UTF-8''" + name)
  res.send(buffer)
})

//向数据库中导入学生名单列表
router.post('/uploadStudentList', upload.single('file'), (req, res, next) => {
  const file = req.file

  if (file) {
    fs.renameSync(
      path.join('./public/uploads', file.filename),
      path.join('./public/uploads', file.filename + '.xlsx')
    )
    const url = path.join(__dirname, `/../public/uploads/${file.filename}.xlsx`)

    const avatarUrl = path.join(__dirname, `/../public/images/1.png`)
    const originData = xlsx.parse(url)[0].data
    // console.log('123', originData)
    const insertData = []
    originData.forEach((item, index) => {
      if (index !== 0) {
        insertData.push({
          stuid: 'stu_' + utils.getUuid(),
          class: item[0].trim(),
          stunum: item[1],
          stuname: item[2].trim(),
          sex: item[3],
          password: '111111',
          avatar: avatarUrl,
        })
      }
    })
    // console.log(insertData)
    sql.insert(Student, insertData).then(() => {
      // fs.unlinkSync(url)
      res.header('Content-Type', 'multipart/form-data')
      res.status(200).send({
        code: 200,
        message: '上传数据成功',
      })
    })
  }

  // console.log(__dirname + './../public/uploads' + file.filename + '.xlsx')
  // console.log(file.path + '\\' + file.filename + '.xlsx')
  // __dirname + './../public/uploads' + file.filename + '.xlsx'
  // var url = `${__dirname}/../public/uploads/${file.filename}.xlsx`
})

module.exports = router
